﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Diagnostics;

namespace NPMonitor.Launcher
{
    static class Program
    {
        /// <summary>
        /// Application entrance
        /// </summary>
        [STAThread]
        static void Main()
        {
            string currProcName = Process.GetCurrentProcess().ProcessName;

            // If current process name already exists, exit program
            if (Process.GetProcessesByName(currProcName).Length > 1)
            {
                MessageBox.Show("There is one running application instance, can't start another instance.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Stop);

                Application.Exit();
            }
            else
            {
                string[] commandLineArguments = Environment.GetCommandLineArgs();

                System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                SingleInstanceManager singleManager = new SingleInstanceManager(new MainForm(NPMonitor.Service.Instance));
                singleManager.Run(new string[] { });

                // Application.Run(new MainForm(NPMonitor.Service.Instance));
            }
        }
        
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            LogUnhandledException(e.Exception);
        }

        private static void LogUnhandledException(Exception ex)
        {
            try
            {
                //This is really a last ditch effort to provide some information when the service doesn't want to start - usually when the config is buggered.  Can't use the default
                //Logging here which is usually specified in config :(
                File.WriteAllText(
                    Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ServiceStartupErrors.txt"), 
                    "Fatal error starting up : " + ex.ToString());
            }
            catch { }
        }
    }
}
